﻿const express = require('express');
const WebSocket = require('ws');
const cors = require('cors');
const bodyParser = require('body-parser');

const app = express();
const port = 3000;

// 中间件配置
app.use(cors());
app.use(bodyParser.json());
app.use(express.static('public'));

// 创建WebSocket服务器
const wss = new WebSocket.Server({ port: 8080 });

// 存储连接的客户端
const clients = new Set();

// WebSocket连接处理
wss.on('connection', (ws) => {
    clients.add(ws);

    ws.on('close', () => {
        clients.delete(ws);
    });
});

// 模拟数据库
let posts = [];
let notifications = [];

// API路由
// 获取帖子列表
app.get('/api/posts', (req, res) => {
    try {
        const page = parseInt(req.query.page) || 1;
        const pageSize = 10;
        const start = (page - 1) * pageSize;
        const end = start + pageSize;

        const paginatedPosts = posts.slice(start, end);

        res.json({
            posts: paginatedPosts,
            hasMore: end < posts.length
        });
    } catch (error) {
        res.status(500).json({ error: '获取帖子失败', details: error.message });
    }
});

// 创建新帖子
app.post('/api/posts', async (req, res) => {
    try {
        const { content, images } = req.body;

        if (!content) {
            return res.status(400).json({ error: '内容不能为空' });
        }

        const newPost = {
            id: Date.now(),
            content,
            images: images || [],
            username: '当前用户',
            avatar: 'avatar.jpg',
            timestamp: new Date(),
            likes: 0,
            comments: []
        };

        posts.unshift(newPost);

        // 向所有连接的客户端发送通知
        const notification = {
            type: 'new_post',
            message: `${newPost.username} 发布了新动态`,
            timestamp: new Date(),
            avatar: newPost.avatar
        };

        broadcastNotification(notification);

        res.status(201).json(newPost);
    } catch (error) {
        res.status(500).json({ error: '发布失败', details: error.message });
    }
});

// 添加评论
app.post('/api/posts/:postId/comments', (req, res) => {
    try {
        const { postId } = req.params;
        const { content } = req.body;

        if (!content) {
            return res.status(400).json({ error: '评论内容不能为空' });
        }

        const post = posts.find(p => p.id === parseInt(postId));
        if (!post) {
            return res.status(404).json({ error: '帖子不存在' });
        }

        const newComment = {
            id: Date.now(),
            content,
            username: '当前用户',
            avatar: 'avatar.jpg',
            timestamp: new Date()
        };

        post.comments.push(newComment);

        // 发送评论通知
        const notification = {
            type: 'new_comment',
            message: `${newComment.username} 评论了你的动态`,
            timestamp: new Date(),
            avatar: newComment.avatar
        };

        broadcastNotification(notification);

        res.status(201).json(newComment);
    } catch (error) {
        res.status(500).json({ error: '评论失败', details: error.message });
    }
});

// 点赞/取消点赞
app.post('/api/posts/:postId/like', (req, res) => {
    try {
        const { postId } = req.params;
        const post = posts.find(p => p.id === parseInt(postId));

        if (!post) {
            return res.status(404).json({ error: '帖子不存在' });
        }

        post.likes = post.likes + 1;
        res.json({ likes: post.likes });
    } catch (error) {
        res.status(500).json({ error: '操作失败', details: error.message });
    }
});

// 广播通知给所有连接的客户端
function broadcastNotification(notification) {
    clients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
            client.send(JSON.stringify(notification));
        }
    });
}

// 错误处理中间件
app.use((err, req, res, next) => {
    console.error(err.stack);
    res.status(500).json({
        error: '服务器错误',
        details: process.env.NODE_ENV === 'development' ? err.message : '请稍后重试'
    });
});

// 启动服务器
app.listen(port, () => {
    console.log(`服务器运行在 http://localhost:${port}`);
}); 